package com.kzd.gtgame.main.game


import android.Manifest
import android.graphics.BitmapFactory
import androidx.lifecycle.LifecycleOwner
import androidx.recyclerview.widget.LinearLayoutManager
import com.blankj.utilcode.util.GsonUtils
import com.kzd.gtgame.R
import com.kzd.gtgame.custom.createViewTextBottom
import com.kzd.gtgame.entity.*
import com.kzd.gtgame.jetpack.vm.GameViewModel
import com.kzd.gtgame.main.game.adapter.*
import com.kzd.gtgame.main.popup.ServiceCodePopup
import com.kzd.gtgame.main.toExternalAppQQ
import com.kzd.gtgame.main.toGameVipActivity
import com.kzd.gtgame.utils.saveImageToGallery
import com.module.lemlin.http.Status

import com.module.lemlin.owner.OwnerViewModeFragment
import kotlinx.android.synthetic.main.include_app_recycler.*
import java.lang.StringBuilder


class GameDetailsFragment : OwnerViewModeFragment<GameViewModel>() {

    companion object {
        fun newInstance(): GameDetailsFragment {
            return GameDetailsFragment()
        }
    }

    private val mServiceCodePopup: ServiceCodePopup by lazy {
        ServiceCodePopup(context = requireContext()) { _, type ->
            val activity = this@GameDetailsFragment.activity
                ?: return@ServiceCodePopup
            viewModel.userPermissions(activity, { isPermissions ->
                if (!isPermissions) {
                    toast("请到设置中开启相关权限")
                    return@userPermissions
                }
                val bitmap = BitmapFactory.decodeResource(resources,
                    if (type == 1) R.mipmap.ic_40008 else R.mipmap.ic_40007)
                val fileName = "${if (type == 1) R.mipmap.ic_40008 else R.mipmap.ic_40007}.png"
                if (saveImageToGallery(activity, bitmap, fileName)) {
                    toast("已保存")
                } else {
                    toast("保存失败")
                }
            }, Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.READ_EXTERNAL_STORAGE)
        }
    }

    private val mDetailsAdapter = DetailsAdapter1()

    override fun viewModel(): GameViewModel {
        return createViewModel(requireActivity())
    }

    override val layoutResId: Int
        get() = R.layout.include_app_recycler

    override fun initView() {
        rvAppRecyclerBody.apply {
            layoutManager = LinearLayoutManager(requireContext())
        }.adapter = mDetailsAdapter

        mDetailsAdapter.setOnItemChildClickListener { _, view, _ ->
            if (view.id == R.id.tvGameDetailsGraphicVip) {
                val title = viewModel.gameDetailsLiveData.value?.data?.data?.name ?: ""
                val vip = viewModel.gameDetailsLiveData.value?.data?.data?.vip
                val vipStr = viewModel.gameDetailsLiveData.value?.data?.data?.vip_str
                val vipJson = GsonUtils.toJson((vip ?: mutableListOf<GameVip>()))
                toGameVipActivity(title, vipJson, vipStr)
            } else if (view.id == R.id.tvGameDetailsNullQQ) {
                //toExternalAppQQ(requireActivity())
                val image = viewModel.userServiceLiveData.value
                    ?.data?.data?.qy_wx_img
                mServiceCodePopup.setContent(if (image.isNullOrEmpty()) {
                    R.mipmap.ic_40008
                } else image, 1)
                    .showPopupWindow()
            }
        }
    }

    override fun initViewMode() {
        viewModel.gameDetailsLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status != Status.SUCCESS)
                return@observe
            val gameDetails: GameDetails = response.data?.data
                ?: return@observe
            val details = mutableListOf<GameDetailsItem<*>>()
            if (!gameDetails.fuli_info.isNullOrEmpty()) {
                val detailsText = GameDetailsItem<Any>(
                    type = ITEM_DETAILS_TEXT, title = "特色", text = gameDetails.fuli_info
                )
                details.add(detailsText)
            }
            if (!gameDetails.fuli_info_str.isNullOrEmpty()) {
                val detailsText = GameDetailsItem<Any>(
                    type = ITEM_DETAILS_NULL, title = "特色", text = gameDetails.fuli_info_str
                )
                details.add(detailsText)
            }
            val detailsGraphic = GameDetailsItem(
                type = ITEM_DETAILS_GRAPHIC,
                title = StringBuilder().append("《")
                    .append(gameDetails.name).append("》VIP表").toString(),
                text = gameDetails.content,
                list = gameDetails.imgs
            )
            details.add(detailsGraphic)
            mDetailsAdapter.setNewInstance(details)

            if (!details.isNullOrEmpty()) {
                mDetailsAdapter.setFooterView(createViewTextBottom(requireContext()))
            }
        })

        viewModel.gameGuessLiveData.observe(this as LifecycleOwner, { response ->
            if (response.status != Status.SUCCESS)
                return@observe
            val gameGuess: MutableList<GameBean> = response.data?.data
                ?: return@observe
            if (gameGuess.isNullOrEmpty())
                return@observe
            val detailsList = GameDetailsItem(
                type = ITEM_DETAILS_GUESS,
                title = "猜你想搜",
                list = gameGuess
            )
            mDetailsAdapter.addData(detailsList)
        })
    }

}